package example.recursive.wordcounter;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;

/**
 * Author: Yu Lin
 */
public class FutureSequencial {
	public static void main(String[] args) throws ExecutionException,
			InterruptedException, FileNotFoundException {
		File startDirectory = new File(
				"src");
		String keyWord = "List";

		System.out.println(new FutureSequencial().compute(startDirectory,
				keyWord));
	}

	public int compute(File startDirectory, String keyWord)
			throws FileNotFoundException {
		int count = 0;
		File[] files = startDirectory.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				count += compute(file, keyWord);
			} else {
				if (search(file, keyWord)) {
					count++;
				}
			}
		}

		return count;
	}

	private boolean search(File file, String keyWord)
			throws FileNotFoundException {
		Scanner scanner = new Scanner(file);
		boolean isMatched = false;
		while (!isMatched && scanner.hasNextLine()) {
			String line = scanner.nextLine();
			if (line.contains(keyWord)) {
				System.out.println(file.getName() + ": " + line);
				isMatched = true;
			}
		}
		return isMatched;
	}
}
